package com.iwhalecloud.bss.kite.cucc.order.accept.chain.impl;

import com.iwhalecloud.bss.kite.common.constant.DcPublicConsts;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.order.accept.chain.AbstractOrderHandler;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ServiceOfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.CustomerOrder;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.OrderItem;
import com.iwhalecloud.bss.kite.dataservice.mapper.order.OrderItemMapper;
import com.iwhalecloud.bss.kite.order.client.dto.OrderRequest;
import com.ztesoft.bss.base.staticdata.CoreDataInteract;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.bss.order.base.consts.KeyValues;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 修正业务相关处理，包括校验和一些初始化
 */
@Component
public class CorrectOrderHandler extends AbstractOrderHandler {

    @Override
    public boolean canHandle(OrderRequest orderRequest) {
        CustomerOrder customerOrder = orderRequest.getOrderContainer().getCustomerOrder();
        String operType = Optional.ofNullable(customerOrder).map(CustomerOrder::getOperType).orElse("");
        if (!Objects.equals(CoreDataInteract.EVT_C_0003_1100, operType)) {
            // 非修正单不处理
            return false;
        }

        return super.canHandle(orderRequest);
    }

    @Override
    public void doHandle(OrderRequest request) {
        OrderItemMapper orderItemMapper = SpringUtil.getBean(OrderItemMapper.class);
        List<OrderItem> oldOrderItems = orderItemMapper.listByCustOrderId(request.getOldCustOrderId(),
            request.getCustId());

        // 判断当前修正业务是否能够修正
        if (!canCorrect(request.getServiceOfferId(), oldOrderItems)) {
            ErrorConsts.ORDER_CORRECT_FORBID_ERROR_3.throwOut();
        }

        // 设置serviceOfferId,如果原订单项只有1条,直接取其服务提供,如果大于1,有相等的,取其服务提供,如果没有，就是销售品修改
        if (oldOrderItems.size() == 1) {
            request.setServiceOfferId(oldOrderItems.get(0).getServiceOfferId());
        }
        else if (oldOrderItems.size() > 1) {
            List<OrderItem> tempOrderItems = oldOrderItems.stream()
                .filter(t -> request.getServiceOfferId().equals(t.getServiceOfferId())).collect(Collectors.toList());
            if (KiteListUtils.isEmpty(tempOrderItems)) {
                request.setServiceOfferId(ServiceOfferConsts.SERVICE_OFFER_MODIFY);
            }
        }

        request.getOrderContainer().setOldOrderItems(oldOrderItems);
    }

    /**
     * 判断当前修正业务是否能够修正
     *
     * @param orderItems
     * @return
     */
    private Boolean canCorrect(String serviceOfferId, List<OrderItem> orderItems) {
        for (OrderItem orderItem : orderItems) {
            if (validateCanUpdateInNewPurchase(orderItem.getApplyObjSpec(), serviceOfferId, KeyValues.XSP_XIUZHEN)
                && validateCanUpdate(orderItem.getServiceOfferId(), orderItem.getOperType())) {
                continue;
            }
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    // 服务提供为新购，订单性质为修正，不允许再修正，去原单上修正
    private boolean validateCanUpdate(String serviceOfferId, String operType) {
        if (StringUtils.isEmpty(operType)) {
            return true;
        }
        String askFlow = ServiceOfferCache.get(serviceOfferId).getAskFlow();
        return dealService(askFlow, operType);

    }

    // 综合办公，不允许对新装业务进行修正，服务提供为新购，订单性质为受理的
    private boolean validateCanUpdateInNewPurchase(String offerId, String serivceOfferId, String askFlow) {
        boolean result = true;
        if (StringUtils.isEmpty(serivceOfferId)) {
            return true;
        }
        for (DcPublic dcPublic : getUndoService()) {
            String currSeriviceOfferId = dcPublic.getStype();
            String currOfferId = dcPublic.getCodea();
            String pcode = dcPublic.getPcode();
            if ((currSeriviceOfferId.equals(serivceOfferId) || "//".equals(currSeriviceOfferId))
                && askFlow.equals(pcode) && currOfferId.indexOf(offerId) > -1) {
                return false;
            }
        }
        return result;
    }

    private boolean dealService(String askFlow, String operType) {
        for (DcPublic dcPublic : getUndoService()) {
            String dcOrderProp = dcPublic.getPkey();
            String dcAskFlows = dcPublic.getCodea();
            String dcPcode = dcPublic.getPcode();
            if ("update".equals(dcPcode)) {
                if (KiteStringUtils.isIndexOf(dcOrderProp, operType, "/")
                    && KiteStringUtils.isIndexOf(dcAskFlows, "//", "/")) { // 所有服务提供
                    return Boolean.FALSE;
                }
                else if (KiteStringUtils.isIndexOf(dcOrderProp, "//", "/") // 所有订单属性
                    && KiteStringUtils.isIndexOf(dcAskFlows, askFlow, "/")) {
                    return Boolean.FALSE;
                }
                else if (KiteStringUtils.isIndexOf(dcOrderProp, operType, "/")
                    && KiteStringUtils.isIndexOf(dcAskFlows, askFlow, "/")) {
                    return Boolean.FALSE;
                }
            }
        }
        return Boolean.TRUE;
    }

    private List<DcPublic> getUndoService() {
        return DcPublicCache.get(DcPublicConsts.DC_ASKFLOWS_NO_ALLOW_CORRECT_PKEY);
    }
}
